package swimv2gm.client.user;

import java.io.IOException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swimv2gm.bl.session.UserManager;

/**
 * Aggiunge le competenze specificate all'utente corrente.
 * 
 * @author Gallesio Matteo
 */
public class AddAbility extends HttpServlet {
	private static final long serialVersionUID = 8924155347106216299L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		UserManager man;
		try {
			man = (UserManager)InitialContext.doLookup("UserManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}

		boolean success;
		Long user = (Long)request.getSession().getAttribute("user");
		if (user == null) {
			success = false;
		}
		else {
			String[] cids = request.getParameterValues("cid");
			if (cids == null || cids.length==0) {
				response.sendRedirect("/SWIMv2gm/abilities/AbilityList?action=add&error=noselection");
				return;
			}
			else {
				long[] cidlist = new long[cids.length];

				try {
					for (int i = 0;i < cids.length;i++) {
						cidlist[i] = Long.parseLong(cids[i]);
					}
					success = man.addAbilities((Long)request.getSession().getAttribute("user"),cidlist);
				} catch (IllegalArgumentException e) {
					success = false;
				}
			}
		}
		response.sendRedirect("/SWIMv2gm/user/Profile?&uid=" + user + "&executed=addabilities&success=" + success);
	}

	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doGet(request,response);
	}

}
